<template>
  <div>
    <div class="pageContent">
      <view class="code">
        <view class="codeMain">
          <view class="codeTit">湘江世纪物业城</view>
          <view class="codeTime">开门密码：{{json.passwordTemp || '暂无'}}</view>
          <view class="imageTestMa"></view>

          <view class="codeTip">二维码对准扫码处 间距在0.8米内</view>
          <view class="codeMess">
            <view>房屋地址: {{json.roomInfo}}</view>
            <view>来访时间: {{json.visitDate}}</view>
            <view>失效时间: {{json.visitEndDate}}</view>
            <view>开门次数: {{json.limitPass}}</view>
            <view v-if="json.audioTextCode">语音密码: {{json.audioTextCode}}</view>
            <view v-if="json.visitorPlate">车牌号码: {{json.visitorPlate}}</view>
          </view>
          <view class="btOne codeTipBt" @click="commitTamp">保存通行码</view>
        </view>
      </view>
      <canvas class="imageTestMa show" canvas-id="canvas"></canvas>
      <!-- <canvas class="canvasCode" canvas-id="canvasCode"></canvas> -->
    </div>

    <canvas class="canvas hidden" canvas-id="myCanvas"></canvas>
    <!-- <canvas class="canvas" canvas-id="myCanvas"></canvas> -->
  </div>
</template>

<script>
  import {
    mapState,
    mapGetters
  } from 'vuex'

  import config from '../../../../static/config.js'
  import drawQrcode from '../../../../static/utils/weapp.qrcode.esm.js'
  import util from '../../../../static/utils/util.js'
  export default {
    data() {
      return {
        modalVisible: false,
        conversation: {},
        isShowChatContainer: true,
        images: config.images,
        localImages: config.localImages,
        mountedCount: 0,
        formData: {
          personCount: '',
          date: '',
          time: '',
        },
        date: '',
        time: '',
        codeText: '8888',
        qrCodeTempTe: '8888',
        // qrCodeTempTe:'MLk1UTrsS0Y=',
        hasToken: true,
        isComplete: false,
        room: '',
        shareImgPath: '',
        codePath: '',
        json: {
          "visitDate": "2021-12-31 12:00",
          "visitEndDate": "2021-12-31 12:00",
          "limitPassNumber": 1,
          qrCodeTemp: "sw121=",
          passwordTemp: 6405,
          "roomInfo": "湘江世纪城-一期-3栋-2002室"
        },
      }
    },
    onLoad() {
      wx.showLoading({
        title: '',
        mask: true,
        duration: 500,
      })
    },
    created() {
      console.warn('subm===comeCode==created执行===')
    },
    methods: {
      toDetail(id) {
        console.warn('toDetail=>', id)
        this.tabIndex = id
      },
      drawCanvas() {
        let self = this;
        return new Promise((resolve, reject) => {
          let systemInfo = wx.getSystemInfoSync();
          let unit = systemInfo.windowWidth / 375;
          // let windowWidth = systemInfo.windowWidth;
          // let screenHeight = systemInfo.screenHeight;
          //设置固定的高度，防止生成的图片变形
          let windowWidth = 375 * unit;
          let screenHeight = 667 * unit;

          var ctx = wx.createCanvasContext("myCanvas", self);
          ctx.setFillStyle('#fff')
          ctx.fillRect(0, 0, 375 * unit, 100 * unit); //画矩形
          var logoUrlTemp = this.localImages + '/mainIcon.png'
          ctx.drawImage(logoUrlTemp, 80 * unit, 38 * unit, 28 * unit, 28 * unit) //画头像icon
          ctx.setFillStyle('#1086FF')
          // ctx.setTextAlign('center')
          ctx.font = 'normal 26px PingFang SC'
          // ctx.setFontSize(23)
          var name = '湘江世纪物业城';
          ctx.fillText(name, 118 * unit, 60 * unit, unit * 220)
          ctx.setFillStyle('#1086FF')
          ctx.fillRect(0, 100 * unit, 375 * unit, 567 * unit); //画矩形
          ctx.setFillStyle('#fff')
          ctx.font = 'normal 36px PingFang SC'
          var name = '开门密码：' + this.json.passwordTemp;
          ctx.fillText(name, 56 * unit, 160 * unit, unit * 250)
          ctx.setFillStyle('#fff')
          ctx.fillRect(56 * unit, 190 * unit, 263 * unit, 305 * unit); //画矩形

          //把生成好的临时二维码图片地址，画二维码
          var logoUrlTemp = this.codePath
          ctx.drawImage(logoUrlTemp, 82.5 * unit, 210 * unit, 210 * unit, 210 * unit) //画头像icon

          ctx.setFillStyle('#000')
          ctx.font = 'normal 14px PingFang SC'
          var name = '二维码对准扫码处 间距在0.8米内';
          ctx.fillText(name, 80 * unit, 460 * unit, unit * 250)
          ctx.font = 'normal 16px PingFang SC'

          ctx.setTextAlign('left')
          ctx.setFillStyle('#fff')
          ctx.font = 'normal 15px PingFang SC'
          var name = '房屋地址:  ' + this.json.roomInfo;
          ctx.fillText(name, 56 * unit, 530 * unit)
          var name = '来访时间:  ' + this.json.visitDate;
          ctx.fillText(name, 56 * unit, 550 * unit, unit * 250)
          var name = '失效时间:  ' + this.json.visitEndDate;
          ctx.fillText(name, 56 * unit, 570 * unit, unit * 250)
          var limitPass = this.json.limitPass
          var name = '开门次数:  ' + limitPass;
          ctx.fillText(name, 56 * unit, 590 * unit, unit * 250)

          if (this.json.audioTextCode && this.json.visitorPlate) {
            var audioTextCode = this.json.audioTextCode
            var name = '语音密码:  ' + audioTextCode;
            ctx.fillText(name, 56 * unit, 610 * unit, unit * 250)
            var visitorPlate = this.json.visitorPlate
            var name = '车牌号码:  ' + visitorPlate;
            ctx.fillText(name, 56 * unit, 630 * unit, unit * 250)
          } else if (this.json.visitorPlate) {
            var visitorPlate = this.json.visitorPlate
            var name = '车牌号码:  ' + visitorPlate;
            ctx.fillText(name, 56 * unit, 610 * unit, unit * 250)
          } else if (this.json.audioTextCode) {
            var audioTextCode = this.json.audioTextCode
            var name = '语音密码:  ' + audioTextCode;
            ctx.fillText(name, 56 * unit, 610 * unit, unit * 250)
          }



          var name = '世纪金源生活服务热线：400-991-5888';
          ctx.fillText(name, 56 * unit, 650 * unit, unit * 250)

          //把画板内容绘制成图片，并回调 画板图片路径
          ctx.draw(false, () => {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: windowWidth * unit,
              height: screenHeight * unit,
              destWidth: windowWidth * unit * 10, // 设置大一点清晰度会高
              destHeight: screenHeight * unit * 10,
              canvasId: 'myCanvas',
              success(res) {
                console.warn('canvasToTempFilePathRes', res);
                // self.setData({
                //     shareImgPath: res.tempFilePath,
                // }
                self.shareImgPath = res.tempFilePath
                resolve()
              },
              fail(res) {
                console.warn('canvasToTempFilePathResFail', res);
                reject()
              },
            })
          })

        });
      },

      commitTamp() {
        let self = this;
        util.tottleOne(() => {
          wx.showLoading({
            title: '保存中...',
            mask: true,
            duration: 2200,
          })
          self.canvasPromise().then(() => {
            self.drawCanvas().then(() => {
              this.wxgetSetting();
            });
          })
        })
        // wx.showToast({
        //     title: '图片下载中，请稍后再试',
        //     icon: 'none',
        // })
      },

      //保存canvas生成的图片到相册
      wxgetSetting() {
        let self = this;
        //（1）获取用户授权的信息
        wx.getSetting({
          success(res) {
            console.warn('getSetting', res);
            //判断scope.writePhotosAlbum的值，若为true则已经授权，直接调用保存到相册的方法；
            if (res.authSetting['scope.writePhotosAlbum']) {
              self.saveImageToPhotosAlbum();
              //若为undefined，则说明是第一次授权，需要调用wx.authorize弹出授权框，授权框只在第一次询问时弹出，如果用户已经拒绝了，则不会弹出。
            } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  self.saveImageToPhotosAlbum();
                },
                fail(res) {
                  console.warn('authorize-fail', res);
                  wx.hideLoading();
                }
              })
            } else {
              wx.hideLoading();
              //若为false,则已经拒绝了授权，这时候我们需要调用wx.openSetting引导用户打开设置，保存到相册
              //wx.openSetting,打开小程序设置页,避免此类滥用情况，微信调整了开启方式，button和对话框Modad确认按钮调用wx.openSetting有效
              wx.showModal({
                title: "温馨提示",
                content: '您没有开启保存相册开关，请点击设置按钮打开',
                confirmText: '去设置',
                cancelText: '取消',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(res) {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          self.saveImageToPhotosAlbum();
                        } else {
                          wx.showToast({
                            title: '您没有开启保存相册开关，无法保存到相册',
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                },
              })
            }
          }
        })
      },

      //画板路径保存成功后，调用方法吧图片保存到用户相册
      saveImageToPhotosAlbum() {
        let self = this;
        console.warn('self.shareImgPath', self.shareImgPath);
        return new Promise((resolve, reject) => {
          wx.saveImageToPhotosAlbum({
            filePath: self.shareImgPath,
            success(res) {
              wx.showToast({
                title: '已保存',
                icon: 'none',
                duration: 2000,
              })
              resolve();
            },
            fail(res) {
              console.warn('saveImageToPhotosAlbum-res', res);
              //技巧1：当错误信息toast无法捕捉，使用弹窗展示
              // wx.showModal({
              //     title: '保存异常',
              //     content: JSON.stringify(res),
              //     success(res) {
              //         if (res.confirm) {
              //         }
              //     },
              // })
              //技巧2：加强展示时间
              wx.showToast({
                title: '保存失败' + res.errMsg,
                icon: 'none',
                duration: 2000,
              })
              reject();
            },
            complete(res) {
              console.warn('complete-saveImageToPhotosAlbum-res', res);
              wx.hideLoading({
                success: (res) => {},
              })
            }
          })
        })
      },

      // 显示二维码
      showQrcode() {
        let self = this;
        let systemInfo = wx.getSystemInfoSync();
        console.warn('systemInfo', systemInfo, this.json)
        let unit = systemInfo.windowWidth / 375;
        var text = this.json.qrCodeTemp;
        drawQrcode({
          width: 210 * unit,
          height: 210 * unit,
          canvasId: 'canvas',
          text: text,
          correctLevel: 3,
          callback: () => {
            console.warn('callback')
          }
        })
      },
      canvasPromise() {
        var self = this;
        return new Promise((resolve, reject) => {
          let systemInfo = wx.getSystemInfoSync();
          let unit = systemInfo.windowWidth / 375;
          console.warn('canvasPromise')
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 210 * unit,
            height: 210 * unit,
            canvasId: 'canvas',
            success(res) {
              console.warn('canvas', res);
              self.codePath = res.tempFilePath
              resolve(res)
            },
            fail(res) {
              console.warn('canvas=Fail', res);
            },
          })
        })
      },

      // 显示二维码,生成临时文件。不要在此处callback函数生成文件，生成码有乱码问题
      showQrcodeTemp() {
        let self = this;
        let systemInfo = wx.getSystemInfoSync();
        let unit = systemInfo.windowWidth / 375;
        var text = this.json.qrCodeTemp;
        drawQrcode({
          width: 210 * unit,
          height: 210 * unit,
          canvasId: 'canvasCode',
          text: text,
          callback: () => {
            console.warn('showQrcodeTemp=callback')
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 210 * unit,
              height: 210 * unit,
              canvasId: 'canvasCode',
              success(res) {
                console.warn('canvasCode', res);
                self.codePath = res.tempFilePath
              },
              fail(res) {
                console.warn('canvasCode=Fail', res);
              },
            })
          }
        })
      },
      //业主获取通行二维码和通行密码
      qrCodeTemp() {
        var roomId = this.room.roomId;
        var url = '/UserServer/owner/qrCode/qrCodeTemp'
        var params = {
          roomId: roomId
        }
        util.wxRequestPro(url, params).then((res) => {
          console.warn('qrCodeTemp=', res, res.param)
          if (res.param) {
            var param = res.param

          }
        })
      },

    },
    onLoad(options) {
      //0.4秒后开始加载页面
      setTimeout(() => {
        this.isComplete = true
      }, 400)

      if (options.json) {
        console.warn('qrCodeTemp=', options.json)
        var dataTemp = decodeURIComponent(options.json);
        console.warn('qrCodeTemp=', dataTemp)
        // var dataTemp = options.json;
        var json = JSON.parse(dataTemp);
        // console.log(dataTemp)
        this.json = json;
        var limitPass = this.json.limitPassNumber == 1 ? '1次' : '不限'
        console.warn('limitPass=', limitPass)
        this.json['limitPass'] = limitPass
      }

      var room = wx.getStorageSync('room');
      if (room) {
        this.room = room;
      }
      this.showQrcode()
    },
    onShow() {
      util.socketTest();
    },
    mounted() {},
    onUnload() {
      console.warn('onUnload')
    },
  }
</script>

<style lang='stylus'>
  .pageContent {
    min-height: 100vh;
    padding: 0rpx 0rpx 0rpx 0rpx;
  }

  .code {
    padding: 0rpx 30rpx 0rpx 30rpx;
  }

  .tabList {
    background: #FFFFFF;
    padding: 30rpx 0rpx 30rpx 30rpx;
    /* border 1px solid #999 */
  }

  .tabItem {
    display: inline-block;
    font-size: 32rpx;
    color: #333333;
    padding: 0rpx 16rpx 0rpx 16rpx;
    /* border 1px solid #666 */
  }

  .tabItem:nth-child(n+2) {
    margin-left: 30rpx;
  }

  .tabSelect {
    font-size: 34rpx;
    font-weight: bold;
  }

  .loginM {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 250rpx 0rpx 0rpx 0rpx;
  }

  .loginMIco {
    width: 240rpx;
    height: 270rpx;
  }

  .loginMBt {
    width: 70%;
  }

  .codeMain {
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 4px 4px 22px 2px rgba(212, 212, 212, 0.39);
    width: 686rpx;
    border-radius: 10rpx;
    padding: 40rpx;
    margin-top: 20rpx;
    background: #FFFFFF;

    /* border 1px solid #666 */
    .codeTime {
      color: #333333;
      font-size: 32rpx;
      padding: 10rpx;
      font-weight: 600;

      .codeRef {
        color: #1086FF;
      }
    }
  }

  .codeTip {
    color: #666666;
    padding: 20rpx 0rpx 20rpx 0rpx;
  }

  .codeTit {
    height: 50rpx;
    font-size: 36rpx;
    font-weight: 600;
    color: #1086FF;
    line-height: 50rpx;
  }

  .imageTestMa {
    height: 420rpx;
    width: 420rpx;
    margin: 0rpx 0rpx 40rpx 0rpx;
    /* border 1px solid aqua */
  }

  .imageTestMa.show {
    position: absolute;
    top: 194rpx;
    left: 50%;
    margin-left: -210rpx;
  }

  .imageTestMa.bottom {
    margin: 20rpx 0rpx 40rpx 50rpx;
  }

  .imageTest {
    position: absolute;
    height: 420rpx;
    width: 420rpx;
    background-color: #ddd;
    margin: 20rpx 0rpx 20rpx 0rpx;
    top: 228rpx;
    left: 50%;
    margin-left: -210rpx;
    /* border 1px solid #bbb */
  }

  .codeTipBt {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0rpx 180rpx 0rpx 180rpx;
  }

  .codeMess {
    text-align: left;
    padding: 30rpx 0rpx 30rpx 0rpx;
  }

  .canvasCode {
    height: 420rpx;
    width: 420rpx;
    margin: 20rpx 0rpx 50rpx 50rpx;
  }

  .canvasCode.hidden {
    position: fixed;
    top: 1000rpx;
    left: 50rpx;
  }

  .canvasCode.show {
    position: absolute;
    top: 194rpx;
    left: 50%;
    margin-left: -210rpx;
  }

  /* canvas二维码画图 */
  .canvas {
    /*    width: 100%;
    height: 100%; */
    width: 750rpx;
    height: 1334rpx;
    /* border: 1rpx solid brown; */
  }

  .canvas.hidden {
    position: fixed;
    top: 2999rpx;
    left: 0;
  }
</style>
